import json
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment


def load_json_result(json_path):
    sort_txt = json_path + '/sort.txt'
    with open(sort_txt, 'r', encoding='utf-8') as f:
        jsons = [x.strip().split('---')[1] for x in f.readlines()]
    results = []
    for j in jsons:
        with open(f'.code_cache/{j}', 'r', encoding='utf-8') as f:
            result = json.load(f)
        results.append(result)
    return results


def write_result_excel(results):
    wb = Workbook()
    ws = wb.active
    ws.append(['类型', '文章名称', '内容规范性', '', '', '',
               '文档描述清晰性', '', '', '',
               '示例代码可用性', '', '', '',
               '示例代码实用性', '', '', '',
               '示例代码规范性', '', '', '',
               '官网信息体验', '', '', '',
               '内容查找便捷性', '', '', '',
               '链接正确性和准确性', '', ''])
    ws.merge_cells('c1:f1')
    ws.merge_cells('g1:j1')
    ws.merge_cells('k1:n1')
    ws.merge_cells('o1:r1')
    ws.merge_cells('s1:v1')
    ws.merge_cells('aa1:ad1')
    ws.merge_cells('ae1:ag1')
    ws.append(['', '', '评分', '是否包含关键错误', '主要问题', '改进建议',
               '评分', '是否包含关键错误', '主要问题', '改进建议',
               '评分', '是否包含关键错误', '主要问题', '改进建议',
               '评分', '是否包含关键错误', '主要问题', '改进建议',
               '评分', '是否包含关键错误', '主要问题', '改进建议',
               '评分', '是否包含关键错误', '主要问题', '改进建议',
               '评分', '是否包含关键错误', '主要问题', '改进建议',
               '是否有链接问题', '问题链接', '问题类型'
               ])
    ws.merge_cells('a1:a2')
    ws.merge_cells('b1:b2')
    for result in results:
        current_row = [result['类型'], result['文章名称']]
        list1 = [result['内容规范性']['评分'], result['内容规范性']['是否含关键错误'],
                 '\n'.join(result['内容规范性']['主要问题']), '\n'.join(result['内容规范性']['改进建议'])]
        list2 = [result['文档描述清晰性']['评分'], result['文档描述清晰性']['是否含关键错误'],
                 '\n'.join(result['文档描述清晰性']['主要问题']), '\n'.join(result['文档描述清晰性']['改进建议'])]
        list3 = [result['示例代码可用性']['评分'], result['示例代码可用性']['是否含关键错误'],
                 '\n'.join(result['示例代码可用性']['主要问题']), '\n'.join(result['示例代码可用性']['改进建议'])]
        list4 = [result['示例代码实用性']['评分'], result['示例代码实用性']['是否含关键错误'],
                 '\n'.join(result['示例代码实用性']['主要问题']), '\n'.join(result['示例代码实用性']['改进建议'])]
        list5 = [result['示例代码规范性']['评分'], result['示例代码规范性']['是否含关键错误'],
                 '\n'.join(result['示例代码规范性']['主要问题']), '\n'.join(result['示例代码规范性']['改进建议'])]
        list6 = [result['官网信息体验']['评分'], result['官网信息体验']['是否含关键错误'],
                 '\n'.join(result['官网信息体验']['主要问题']), '\n'.join(result['官网信息体验']['改进建议'])]
        list7 = [result['内容查找便捷性']['评分'], result['内容查找便捷性']['是否含关键错误'],
                 '\n'.join(result['内容查找便捷性']['主要问题']), '\n'.join(result['内容查找便捷性']['改进建议'])]
        current_row = current_row + list1 + list2 + list3 + list4 + list5 + list6 + list7
        print(current_row)
        ws.append(current_row)
    wb.save('1.xlsx')


def write_result_excel_v2(results):
    wb = Workbook()
    ws = wb.active
    ws.append(['类型', '文章名称', '问题类型', '评分', '是否含关键错误', '主要问题', '改进建议'])
    for result in results:
        current_row = [result['类型'], result['文章名称']]
        if result.get('error'):
            try:
                ws.append(current_row + [result['data']['payload']['content']])
            except Exception as e:
                ws.append(current_row + [e])
            finally:
                continue
        for k, v in result.items():
            if isinstance(v, dict):
                ws.append(current_row + [k, v['评分'], v['是否含关键错误'], '\n\n'.join(v['主要问题']),
                                         '\n\n'.join(v['改进建议'])])
    wb.save('result_ai.xlsx')


def write_result_excel_v3(results):
    wb = Workbook()
    ws = wb.active
    ws.append(['产品', '文章名称', '问题类型', '子问题类型', '上下文', '主要问题', '改进建议'])
    for result in results:
        print(result)
        current_row = [result['类型'], result['文章名称']]
        if result.get('error'):
            try:
                ws.append(current_row + ['API调用失败' + result['data']['payload']['content']])
            except Exception as e:
                ws.append(current_row + [f'{result}'])
            finally:
                continue
        for k, v in result.items():
            current_row = [result['类型'], result['文章名称']]
            if isinstance(v, list):
                # print(result['文章名称'])
                if k == '链接问题':
                    current_row = current_row + ['内容规范性']
                    if len(v) == 0:
                        continue
                    for url_question in v:
                        subclass_of_problem = '链接错误'
                        if '锚点' in url_question[2]:
                            subclass_of_problem = '链接问题-锚点错误'
                        elif '重定向' in url_question[2]:
                            subclass_of_problem = '链接问题-重定向'
                        elif '页面不存在' in url_question[2]:
                            subclass_of_problem = '链接问题-页面不存在'
                        ws.append(current_row + [subclass_of_problem, f'{url_question[0]} {url_question[1]}', url_question[2], '链接问题请检查'])
                else:
                    current_row = current_row + [k]
                    for question in v:
                        if not question.get('主要问题'):
                            question['主要问题'] = ''
                        else:
                            if isinstance(question['主要问题'], list):
                                main_question = '\n'.join(question['主要问题'])
                                suggest = '\n'.join(question['改进建议'])
                                ws.append(
                                    current_row + [question['子问题类型'], question['上下文'], main_question,
                                                   suggest])
                            else:
                                suggest = '\n'.join(question['改进建议']) if isinstance(question['改进建议'], list) else question['改进建议']
                                ws.append(current_row + [question['子问题类型'], question['上下文'], question['主要问题'],
                                                         suggest])
    set_excel_format(ws)
    wb.save('result_ai.xlsx')


def set_excel_format(worksheet):
    """设置表格格式"""
    # 定义样式
    font = Font(name='微软雅黑', size=11)
    wrap_alignment = Alignment(wrap_text=True, horizontal='left', vertical='top')

    # 设置列宽
    worksheet.column_dimensions['A'].width = 15
    worksheet.column_dimensions['B'].width = 30
    worksheet.column_dimensions['C'].width = 20
    worksheet.column_dimensions['D'].width = 20
    worksheet.column_dimensions['E'].width = 45
    worksheet.column_dimensions['F'].width = 45
    worksheet.column_dimensions['G'].width = 45

    # 应用字体和对齐方式
    for row in worksheet.iter_rows():
        for cell in row:
            cell.font = font
            cell.alignment = wrap_alignment

        # 估算行高
        max_lines = max((len(str(cell.value)) // 45 + 1 for cell in row), default=1)
        worksheet.row_dimensions[row[0].row].height = max_lines * 20


if __name__ == '__main__':
    analyzer_results = load_json_result('.code_cache')
    write_result_excel_v3(analyzer_results)
